﻿using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace Onshi.POS.AccesoDatos
{
    /// <summary>
    /// Clase que permite ejecutar packetes dts desde las plantilla dtsx o desde el Sql Server
    /// </summary>
    public class ServicioDatosDts
    {
        #region Atributos
        private String oledbConenction = String.Empty;
        #endregion

        #region Constructor
        public ServicioDatosDts(String OLEDBConnection)
        {
            oledbConenction = OLEDBConnection;        
        }
        #endregion

        #region Metodos
        public void EjectarPaquete(String tipo, String directorio, String nombrePaquete)
        {
            Application application = null;
            Package package = null;
            try
            {
                application = new Application();

                if (!System.IO.File.Exists(String.Format("{0}\\{1}.dtsx", directorio, nombrePaquete)))
                    throw new Exception(String.Format("El paquete no exite en el directorio [{1}]", directorio));

                package = new Package();
                switch (tipo)
                {
                    case "file":
                        application.LoadPackage(String.Format("{0}\\{1}.dtsx", directorio, nombrePaquete), null);
                        break;
                    case "sql":
                        application.LoadFromSqlServer2(String.Format("{0}\\{1}.dtsx", directorio, nombrePaquete), this.oledbConenction, null);
                        break;
                }

                package.Execute();
                if (package.ExecutionResult == DTSExecResult.Failure)
                {
                    String error = String.Empty;
                    foreach(var err in package.Errors)
                    {
                        error = String.Format("Source: {0}.\n\r Descripción: {1}.", err.Source, err.Description);
                    }
                    throw new Exception(error);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
